package com.gl.basis.common.exception.handler;

import com.gl.basis.common.exception.AccessException;
import com.gl.basis.common.exception.AuthException;
import com.gl.basis.common.exception.BusinessException;
import com.gl.basis.common.pojo.Page;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理器
 * @data 2019年12月2日 11点49分
 */
@RestControllerAdvice
@ResponseStatus(HttpStatus.OK)
public class GlobalExceptionHandler {
    /**
     *参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Page bindException(BindException e){
        Page page = new Page();
        StringBuffer msg=new StringBuffer();
        for (FieldError fieldError : e.getFieldErrors()) {
            msg.append(" ").append(fieldError.getDefaultMessage());
        }
        page.setSuccess(false);
        page.setMsg(msg.toString());
        return page;
    }

    /**
     * 认证异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {AccessException.class, AuthException.class})
    public Page authException(Exception e) {
        Page page = new Page();
        page.setSuccess(false);
        page.setMsg(e.getMessage());
        return page;
    }

    /**
     * 业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class )
    public Page businessException(BusinessException e) {
        Page page = new Page();
        page.setSuccess(false);
        page.setMsg(e.getMessage());
        return page;
    }
}
